﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Text;

namespace rabbit_mq_publisher
{
    internal class Program
    {
        static async Task Main()
        {
            /*
             * 大概流程
             * 1.连接: 首先建立与队列服务的连接
             * 2.通道: 再通过连接创建会话通道连接交换机
             * 3.交换机: 交换机根据路由将数据存储到队列
             * 4.队列: 存储数据
             */

            var factory = new ConnectionFactory
            {
                UserName = "guest",
                Password = "guest",
                HostName = "localhost"
            };

            string exchangeName = "direct_exchange";
            string queueName = "direct_queue";
            string routingKey = "direct_data";

            var conn = await factory.CreateConnectionAsync();
            var channel = await conn.CreateChannelAsync();
            await channel.ExchangeDeclareAsync(exchangeName, ExchangeType.Direct);

            await channel.QueueDeclareAsync
                (queueName, false, false, false, null);

            await channel.QueueBindAsync(queueName, exchangeName, routingKey, null);

            while (true) 
            {
                Console.WriteLine("开始发布消息");

                var data = new
                {
                    Type = "Direct",
                    CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")
                };

                var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
                var props = new BasicProperties
                {
                    ContentType = "text/plain",
                    DeliveryMode = DeliveryModes.Persistent, // 持久化存储
                    //Expiration = "5000" // 过期时间(毫秒)
                };

                await channel.BasicPublishAsync(exchangeName, routingKey, true, props, body);

                Console.WriteLine("发布消息完成");

                Thread.Sleep(1000);
            }
        }
    }
}
